import { createSlice } from '@reduxjs/toolkit'
import { TUser } from '../../types'
import { userApiSlice } from '../../../api/userApiSlice'

type TUserState = {
	data: TUser | null
	token: string
}

const initialState: TUserState = {
	data: null,
	token: '',
}

const sliceName = 'user'

export const userSlice = createSlice({
	name: sliceName,
	initialState,
	reducers: {
		setUserLogOut: (state) => {
			state.token = ''
			state.data = null
		},
	},
	extraReducers: (builder) => {
		builder.addMatcher(
			userApiSlice.endpoints.editUser.matchFulfilled,
			(state, { payload }) => {
				state.data = payload
			}
		)
		builder.addMatcher(
			userApiSlice.endpoints.signIn.matchFulfilled,
			(state, { payload }) => {
				state.token = payload.token
				state.data = payload.data
			}
		)
	},
})
